var express = require('express')
var path = require('path')
var fs = require('fs')
var router = express.Router()

/* GET home page. */
// router.get('/', function (req, res, next) {
//   res.render('index', { title: 'Express' })
// })

router.get('/maps/:mapId', function (req, res) {
  let { params: { mapId } } = req
  let file = `../static/map/${mapId}.json`
  let map = require(file)
  res.send(map)
})

router.post('/maps', function (req, res) {
  let { body } = req
  fs.readdir('./static/map', ((err, files) => {
    if (!err) {
      let length = files.length
      fs.writeFile(`./static/map/${length + 1}.json`, JSON.stringify(body), err1 => {
        if (err1) {
          console.log(err1)
          res.send({
            code: -1,
            msg: 'server error'
          })
        } else {
          res.send({
            code: 1,
            msg: 'success',
          })
        }
      })
    } else {
      console.log(err)
      res.send({
        code: -1,
        msg: 'server error'
      })
    }
  }))
})

router.put('/maps/:mapId', function (req, res) {
  let { body, params } = req
  let { mapId } = params
  fs.writeFile(`./static/map/${mapId}.json`, JSON.stringify(body), err1 => {
    if (err1) {
      console.log(err1)
      res.send({
        code: -1,
        msg: 'server error'
      })
    } else {
      res.send({
        code: 1,
        msg: 'success',
      })
    }
  })
})

router.get('/count/maps', function (req, res) {
  fs.readdir('./static/map', ((err, files) => {
    if (!err) {
      let length = files.length
      res.send({
        code: 1,
        data: {
          length
        }
      })
    } else {
      console.log(err)
      res.send({
        code: -1,
        msg: 'server error'
      })
    }
  }))
})

module.exports = router
